package cn.icanci.loopstack.amc.cloud.dal.mongodb.mongo;

import cn.icanci.loopstack.amc.cloud.dal.mongodb.daointerface.GroupDAO;
import cn.icanci.loopstack.amc.cloud.dal.mongodb.dataobject.GroupDO;
import cn.icanci.loopstack.amc.common.model.PageList;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @author icanci
 * @since 1.0 Created in 2023/01/15 12:24
 */
@Service("groupDAO")
public class MongoGroupDAO extends AbstractBaseDAO<GroupDO> implements GroupDAO {

    @Override
    public void insert(GroupDO group) {
        super.insert(group);
        mongoTemplate.insert(group, COLLECTION_NAME);
    }

    @Override
    public void update(GroupDO group) {
        super.update(group);
        mongoTemplate.save(group, COLLECTION_NAME);
    }

    @Override
    public List<GroupDO> queryAll() {
        Criteria criteria = Criteria.where(GroupColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.find(query, COLLECTION_CLASS, COLLECTION_NAME);
    }

    @Override
    public PageList<GroupDO> pageQuery(GroupDO group, int pageNum, int pageSize) {
        Criteria criteria = Criteria.where(GroupColumn.env).is(DEFAULT_ENV);

        if (StringUtils.isNotBlank(group.getGroupName())) {
            // 不分区大小写查询，其中操作符"i"：表示不分区大小写
            criteria.and(GroupColumn.groupName).regex("^.*" + group.getGroupName() + ".*$", "i");
        }

        if (StringUtils.isNotBlank(group.getGroupId())) {
            criteria.and(GroupColumn.groupId).is(group.getGroupId());
        }

        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC, GroupColumn.createTime));

        return pageQuery(query, COLLECTION_CLASS, pageSize, pageNum, COLLECTION_NAME);
    }

    @Override
    public GroupDO queryOneById(String _id) {
        Criteria criteria = Criteria.where(GroupColumn._id).is(_id);
        criteria.and(GroupColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);
    }

    @Override
    public GroupDO queryByGroupId(String groupId) {
        Criteria criteria = Criteria.where(GroupColumn.groupId).is(groupId);
        criteria.and(GroupColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);
    }

    @Override
    public GroupDO queryByGroupName(String groupName) {
        Criteria criteria = Criteria.where(GroupColumn.groupName).is(groupName);
        criteria.and(GroupColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);
    }
}
